<template>
  <VPage>
    <VTable ref="tableRef" v-bind="tableOptins" class="is--card">
      <template #form="{ form }">
        <select-category
          class="w-40"
          v-model="form.product_category"
          placeholder="产品分类"
          :defaultProps="defaultProps"
          @change="changeCategory"
        ></select-category>
        <VGroup>
          <el-select class="selectClass !w-[120px]" v-model="form.skuRange.type">
            <el-option
              v-for="item in skuOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
          <multi-input
            v-model="form.skuRange.value"
            placeholder="SKU"
            class="w-40"
          ></multi-input>
        </VGroup>
        <multi-input v-model="form.spu" placeholder="SPU" class="w-40"></multi-input>
        <VGroup>
          <el-select class="selectClass !w-[120px]" v-model="form.nameRange.type">
            <el-option
              v-for="item in nameOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
          <el-input
            v-model="form.nameRange.value"
            placeholder=""
            clearable
            class="w-40 h-8"
          />
        </VGroup>
        <VGroup>
          <el-select class="selectClass !w-[120px]" v-model="form.personRange.type">
            <el-option
              v-for="item in personOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
          <select-personnel
            class="w-40"
            v-model="form.personRange.value"
            :multiple="true"
          ></select-personnel>
        </VGroup>
        <VGroup>
          <el-select class="selectClass !w-[120px]" v-model="form.timeRange.type">
            <el-option
              v-for="item in timeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
          <el-date-picker
            v-model="form.timeRange.value"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="max-width: 300px"
            :default-time="defaultTime()"
          />
        </VGroup>
        <el-select
          class="!w-[150px]"
          v-model="form.combined_sources"
          placeholder="组合类型"
          clearable
        >
          <el-option
            v-for="item in options['goods.GoodsSpu']?.[0].combinedSourcesText"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </template>
      <template #toolbar_btns>
        <div class="w-full">
          <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
            <el-tab-pane
              :label="item.label"
              :name="item.name"
              v-for="(item, index) in tabList"
              :key="index"
            >
              <template #label>
                {{ item.label }}(<span
                  :class="activeName == item.name ? 'base-text-color' : 'text-[#999999]'"
                  >{{ item.count }}</span
                >)
              </template>
            </el-tab-pane>
          </el-tabs>
        </div>
        <el-button type="primary" @click="batchAudit()">批量审核</el-button>
      </template>
    </VTable>
  </VPage>
  <BatchAudit ref="batchRef" @query="queryForm"></BatchAudit>
  <DerivedCenter ref="DerivedCenterRef"></DerivedCenter>
</template>
<script setup name="Goods-managementCombination-sku" lang="jsx">
import { ElMessage, ElMessageBox } from "element-plus";
import { nextTick, ref, reactive, toRefs } from "vue";
import { queryCombinationSkuList } from "./api";
import { getOptions } from "@/api/index.js";
import BatchAudit from "./components/BatchAudit";
import VImage from "@/components/Image/index.vue";
import SelectCategory from "@/components/SelectCategory";
import DerivedCenter from "@/components/DerivedCenter";
import { skuOptions, nameOptions, personOptions, timeOptions } from "./data.js";
import { useRouter } from "vue-router";
import SKUInfo from "./components/SKUInfo";
const router = useRouter();

const defaultProps = {
  children: "son",
  label: "name",
  value: "id",
  checkStrictly: false,
  multiple: true,
};

const changeCategory = (val) => {
  if (val && val.length) {
    const lastLevelIDs = val.map((categoryPath) => categoryPath[categoryPath.length - 1]);
    const form = tableRef.value.getForm();
    setForm({ ...form, spu_category: lastLevelIDs });
  } else {
    const form = tableRef.value.getForm();
    setForm({ ...form, spu_category: 0 });
  }
};

// 获取
const fetchOption = () => {
  getOptions({
    name: [
      "goods.GoodsSpu",
      "goods.GoodsSku",
      "goods.GoodsSkuSalesInfo",
      "goods.GoodsSkuSupplier",
      "goods.GoodsSkuAccessories",
      "goods.GoodsSkuSupplier",
      "gallery.GoodsSkuGalleryContents",
    ],
  }).then((res) => {
    options.value = res.data;
  });
};
fetchOption();

const tableRef = ref();

const tableOptins = reactive({
  rowConfig: { height: "auto" },
  showHeaderOverflow: false,
  showOverflow: false,
  scrollY: { enabled: false },
  formConfig: {
    data: {
      combination_review_status: "",
      shop_id: "",
      create_time: "",
      status: "",
      operations_personnel: "",
      skuRange: { type: "custom_sku", value: "", range: false },
      nameRange: { type: "sku_cn_title", value: [], range: true },
      personRange: { type: "developer_id", value: [], range: true },
      timeRange: { type: "dev_add_time", value: [], range: true },
    },
  },
  columns: [
    { type: "checkbox", width: "40" },
    {
      field: "name",
      title: "产品",
      width: "450",
      treeNode: "tree-node",
      slots: {
        default: ({ row, level }) => {
          return (
            <div class="flex justify-start py-2">
              <div class="relative" style="width:100px;height:100px">
                <VImage
                  src={row.attr_img_watermark || row.attr_img}
                  width={80}
                  height={80}
                ></VImage>
              </div>
              <div class="ml-3 flex-1">
                <div class="w-full flex justify-start mb-1">
                  <div class="truncate flex-1 w-24 text-[14px]">
                    {row.sku}
                    {level == 1 ? `(${row.spu})` : ""}
                  </div>
                </div>
                <div class="w-full mb-1">
                  <span class="w-56 mr-2">自定义SKU:{row.custom_sku || "--"}</span>
                </div>
                <el-tooltip
                  class="item"
                  effect="dark"
                  content={row.spu_category_text}
                  placement="top"
                >
                  <div class="flex justify-start mb-1 overflow-line2">
                    {row.spu_category_text || "--"}
                  </div>
                </el-tooltip>
              </div>
            </div>
          );
        },
      },
    },
    {
      field: "product-name",
      title: "产品名称",
      width: "400",
      slots: {
        default: ({ row }) => {
          return (
            <div>
              <el-tooltip
                class="item"
                effect="dark"
                content={row.sku_cn_title}
                placement="top"
              >
                <div class="overflow-line2" style="width: 380px">
                  {row.sku_cn_title}
                </div>
              </el-tooltip>
              <el-tooltip
                class="item"
                effect="dark"
                content={row.sku_en_title}
                placement="top"
              >
                <div class="overflow-line2" style="width: 380px">
                  {row.sku_en_title}
                </div>
              </el-tooltip>
            </div>
          );
        },
      },
    },
    {
      field: "product-name",
      title: "子SKU信息",
      width: "300",
      slots: {
        default: ({ row }) => {
          return (
            <SKUInfo
              list={row.goods_sku_combination_sku}
              show-expand={row?.goods_sku_combination_sku?.length > 2}
              handleExpand={(visible) => expandFixedRow(rowIndex, visible)}
            ></SKUInfo>
          );
        },
      },
    },
    {
      field: "product-type",
      title: "审核状态",
      width: "130",
      slots: {
        default: ({ row }) => {
          return (
            <div>
              <div
                class={
                  row.combination_review_status == 1
                    ? "tag-status1"
                    : row.combination_review_status == 2
                    ? "tag-status2"
                    : row.combination_review_status == 3
                    ? "tag-status3"
                    : "tag-status3"
                }
              >
                {row.combination_review_status_text}
              </div>
              <div class="text-xs text-gray-500 mt-1">{row.dev_review_remark}</div>
            </div>
          );
        },
      },
    },
    {
      field: "product-type",
      title: "组合类型",
      width: "130",
      slots: {
        default: ({ row }) => {
          return (
            <div>
              <div>{row.combined_sources_text || "--"}</div>
            </div>
          );
        },
      },
    },
    {
      field: "operator",
      title: "人员",
      width: "160",
      slots: {
        default: ({ row }) => {
          return (
            <div>
              <div class="pt-1">
                添加: <span>{row.create_user_text || "--"}</span>{" "}
              </div>
              <div class="pt-1">
                开发: <span>{row.developer_text || "--"}</span>
              </div>
              <div class="pt-1">
                审核: <span>{row.dev_reviewer_text || "--"}</span>
              </div>
            </div>
          );
        },
      },
    },
    {
      field: "operator-time",
      title: "操作时间",
      width: "220",
      slots: {
        default: ({ row }) => {
          return (
            <div>
              <div class="text-xs pt-1">
                开发添加: <span>{row.dev_add_time || "--"}</span>
              </div>
              <div class="text-xs pt-1">
                运营审核: <span>{row.operation_review_time || "--"}</span>
              </div>
              <div class="text-xs pt-1">
                开发审核: <span>{row.dev_review_remark || "--"}</span>
              </div>
            </div>
          );
        },
      },
    },
  ],
  proxyConfig: {
    seq: true,
    props: {
      result: "data",
      total: "total",
    },
    autoLoad: false,
    ajax: {
      query: async ({ page, form }) => {
        const res = await queryCombinationSkuList({ ...form, ...page });
        getCount(res.data.count);
        const totalItem = res.data.count.find((i) => i.key == activeName.value);
        return new Promise(function (resolve) {
          resolve({
            data: res.data.list,
            total: totalItem?.doc_count,
          });
        });
      },
    },
  },
});

const activeName = ref("");
const data = reactive({
  tabList: [
    {
      label: "全部",
      name: "",
      count: 0,
    },
    {
      label: "待审核",
      name: 0,
      count: 0,
    },
    {
      label: "审核通过",
      name: 1,
      count: 0,
    },
    {
      label: "审核未通过",
      name: 2,
      count: 0,
    },
  ],
  options: [],
});
const { tabList, options } = toRefs(data);

const getCount = (countList) => {
  tabList.value = tabList.value.map((i) => {
    countList.filter((j) => {
      if (i.name === j.key) {
        i.count = j.doc_count;
      }
    });
    return i;
  });
};

//更新表格数据
const refresh = () => {
  tableRef?.value.$table.commitProxy("query");
};
//获取已选中的行
const getSelectRow = () => {
  return tableRef?.value.$table.getCheckboxRecords();
};

// 批量审核
const batchRef = ref();
const batchAudit = async (status) => {
  const records = getSelectRow();
  const skuIds = records.map((i) => i.id);
  if (skuIds.length == 0) {
    ElMessage.error("至少选择一项");
    return;
  }
  batchRef.value.open(skuIds);
};

const handleClick = (val) => {
  tableRef.value.setForm({
    combination_review_status: val.props.name,
  });
  refresh();
};
const queryForm = () => {
  const form = tableRef.value.getForm();
  tableRef.value.setForm({ ...form });
  nextTick(() => {
    tableRef.value.query();
  });
};

// 查看
const handleView = (spuId) => {
  router.push({
    path: "/task/product/detail",
    query: {
      spuId,
    },
  });
};

const setForm = (val) => {
  nextTick(() => {
    tableRef.value.setForm(val);
  });
};

const expandFixedRow = (rowIndex, visible) => {
  const beforeExpandActives = deepClone(expandActives.value);
  let needSplice;
  if (rowIndex || rowIndex === 0) {
    const _findIndex = beforeExpandActives.findIndex((v) => v === rowIndex);
    if (visible && _findIndex > -1) {
      needSplice = _findIndex;
    } else {
      beforeExpandActives.push(rowIndex);
    }
  }
  nextTick(() => {
    TKTableUtils.expandFixedRow(beforeExpandActives);
    if (typeof needSplice === "number" && needSplice > -1) {
      beforeExpandActives.splice(needSplice, 1);
    }
    expandActives.value = beforeExpandActives;
  });
};
</script>
<style lang="scss" scoped>
.selectClass {
  &:deep(.el-select__wrapper) {
    background-color: var(--base-small-bg-color) !important;
  }
}

:deep(.el-tabs__nav-wrap::after) {
  height: 1px;
}
:deep(.vxe-toolbar) {
  padding-top: 8px;
}
</style>
<style>
.tag {
  padding: 4px 7px;
  border-radius: 4px;
  display: inline-block;
  font-size: 12px;
}

.tag-status1 {
  padding: 4px 7px;
  border-radius: 4px;
  display: inline-block;
  font-size: 12px;
  color: #faad14;
  background-color: rgba(250, 173, 20, 0.1);
}

.tag-status2 {
  padding: 4px 7px;
  border-radius: 4px;
  display: inline-block;
  font-size: 12px;
  color: #3a4259;
  background-color: rgba(58, 66, 89, 0.1);
}

.tag-status3 {
  padding: 4px 7px;
  border-radius: 4px;
  display: inline-block;
  font-size: 12px;
  color: #ff0000;
  background-color: rgba(255, 0, 0, 0.1);
}

:deep(.el-tabs__nav-wrap::after) {
  height: 1px;
}

.child-sku {
  border-radius: 4px 4px 0px 0px;
  border: 1px solid #e6e7e9;
  padding: 5px;
  position: relative;
}

.child-quantity {
  position: absolute;
  right: 0;
  top: 0;
  color: #3487ff;
  background: #ebecee;
  border-radius: 0px 4px 0px 4px;
  padding: 0px 3px;
  font-size: 12px;
}
</style>
